import QRCode from '@/components/QRCode';
import type { RequestConfig } from '@umijs/max';
import { Modal, message } from 'antd';

// 运行时配置

function loginHandle() {
  if (window.__modal) {
    return;
  }
  window.__modal = true;
  Modal.confirm({
    title: '登录过期，请扫码登录',
    destroyOnClose: true,
    content: <QRCode />,
    footer: null,
    afterClose() {
      window.__modal = false;
    },
  });
}

export function render(oldRender) {
  oldRender();
  // ssoLogin().then((res) => {
  //   if (res?.data?.failReason) {
  //     loginHandle();
  //   } else {
  //     oldRender();
  //   }
  // });
}

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<{ name: string }> {
  return { name: '123' };
}

export const request: RequestConfig = {
  timeout: 10000,
  withCredentials: true,
  baseURL: 'http://localhost:3000',
  // other axios options you want
  errorConfig: {
    errorHandler(err) {
      console.log('errorHandler', err);
      loginHandle();
      message.error(err.message || '系统错误');
    },
    errorThrower() {
      console.log('errorThrower');
      message.error('errorThrower');
    },
  },
  requestInterceptors: [
    (config) => {
      // 在这里处理 FormData
      if (
        config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
      ) {
        // 如果 Content-Type 设置为 application/x-www-form-urlencoded
        // 我们需要将 FormData 转换为字符串形式
        if (config.data) {
          const formData = Object.keys(config.data)
            .map(
              (key) =>
                encodeURIComponent(key) +
                '=' +
                encodeURIComponent(config.data[key]),
            )
            .join('&');
          config.data = formData;
        }
      }
      return config;
    },
  ],
  responseInterceptors: [
    async (response: any) => {
      console.log('responseInterceptors');
      const success = response?.data?.success;
      if (!success) {
        throw response.data;
      }
      return response;
    },
  ],
};

export const layout = () => {
  return {
    logo: 'https://chd.web.sdo.com/favicon.ico',
    menu: {
      locale: false,
    },
    logout: () => {},
  };
};
